<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if(!class_exists('CI_Model')) { class CI_Model extends Model {} }

class Feedback_model extends CI_Model {
	var $perpage = 10;
	var $url;
	public function __construct() {
	   parent::__construct();
	   $this->url = $this->uri->segment(1);
		$this->input->enable_hspc();
	}
	public function index() {

		$form = new jQuickForm('pg_simple');

		$form->setLabel('<a name="thisform"></a>Обратная связь');

		$fieldset = $form->insertFieldset();
		$gr = $fieldset->insertGroup()->addClass('col col2');
		$gr->insertInputText('feedback_name')->setLabel('Ваше имя')->addRuleRequired();

		/*$phone = $gr->insertInputText('feedback_phone')->setLabel('Телефон');
		$phone->addRule('callback', 'Не верный формат поля', array('callback' => 'validate_phone'), HTML_QuickForm2_Rule::CLIENT);
		$phone->addRule('callback', 'Не верный формат поля', array('callback' => 'validate_phone'), HTML_QuickForm2_Rule::SERVER);
		$phone->addRuleRequired();*/

		$email = $gr->insertInputText('feedback_email')->setLabel('Электронная почта');
		$email->addRule('callback', 'Не верный формат поля', array('callback' => 'validate_email'), HTML_QuickForm2_Rule::CLIENT);
		$email->addRule('callback', 'Не верный формат поля', array('callback' => 'validate_email'), HTML_QuickForm2_Rule::SERVER);
		$email->addRuleRequired();

		$fieldset->insertTextArea('feedback_text')->setLabel('Текст обращения')->addRuleRequired();

		$this->tools_model->captcha($fieldset);

		if ($_SERVER['REQUEST_METHOD'] == "POST" && $form->validate()) {
			$mail_data = $p_data = $this->input->post();
			$this->load->library('email');

			$msg = $this->load->view('modules/feedback/email', $mail_data, true);

			$this->email->from($this->config->item('from_email'), $this->config->item('from_name'));
			$this->email->to($this->config->item('admin_email'));
			$this->email->subject('Сообщение обратной связи с сайта '.$this->config->item('company_name'));
			$this->email->message($msg);

			if ($this->email->send()) {
				$this->session->set_flashdata('msg', 'Спасибо, Ваше сообщение отправлено.');
			} else {
				$this->session->set_flashdata('msg', 'Ошибка отправки сообщения.');
			}

			$hidden = sha1("soltbyme".$this->session->userdata('session_id')."mybigsolthash");
			$hidden2 = sha1("soltbyme".$this->session->userdata('session_id')."myhashsolt");
			unset($mail_data[$hidden]);
			unset($mail_data[$hidden2]);
			$mail_data['feedback_id'] = 0;
			$mail_data['feedback_date'] = time();
			$mail_data['feedback_ip'] = $this->input->ip_address();
			$this->db->insert('feedback', $mail_data);
			redirect($this->url.'/');
		}

		$form->insertInputSubmit('Отправить');

		if ($this->ion_auth->logged_in()) {
			$user = $this->ion_auth->get_user();
			$have_data['feedback_name'] = $user->first_name." ".$user->last_name;
			$have_data['feedback_phone'] = $user->phone;
			$have_data['feedback_email'] = $user->email;
		}

		$form->addDataSource(new HTML_QuickForm2_DataSource_Array($have_data));
		$data['form'] = $form."";
		$data['js'] = jQuickForm::js()->getJsAll();

		$out['text'] = $this->load->view('modules/feedback/index', $data, true);
		return $out;
	}
	public function ask_qestion() {

		$form = new jQuickForm('ask_qestion');

		if ($this->input->get('item_id')) {
			$form->addElement('hidden', 'item_id')->setValue($this->input->get('item_id'));
		}

		if ($this->input->server('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest') {
			$form->addElement('hidden', 'XMLHttpRequest')->setId('XMLHttpRequest')->setValue(md5('showmemymoney'));
		}

		$form->setLabel('<a name="thisform"></a>Задать вопрос');

		$gr = $form->insertGroup()->addClass('col col2');
		$gr->insertInputText('feedback_name')->setLabel('Ваше имя')->addRuleRequired();

		/*$phone = $gr->insertInputText('feedback_phone')->setLabel('Телефон');
		$phone->addRule('callback', 'Не верный формат поля', array('callback' => 'validate_phone'), HTML_QuickForm2_Rule::CLIENT);
		$phone->addRule('callback', 'Не верный формат поля', array('callback' => 'validate_phone'), HTML_QuickForm2_Rule::SERVER);
		$phone->addRuleRequired();*/

		$email = $gr->insertInputText('feedback_email')->setLabel('Электронная почта');
		$email->addRule('callback', 'Не верный формат поля', array('callback' => 'validate_email'), HTML_QuickForm2_Rule::CLIENT);
		$email->addRule('callback', 'Не верный формат поля', array('callback' => 'validate_email'), HTML_QuickForm2_Rule::SERVER);
		$email->addRuleRequired();

		$form->insertTextArea('feedback_text')->setLabel('Текст вопроса')->addRuleRequired();

		$this->tools_model->captcha($form);

		if ($_SERVER['REQUEST_METHOD'] == "POST" && $form->validate()) {
			$mail_data = $p_data = $this->input->post();
			$this->load->library('email');

			if (is_numeric($p_data['item_id'])) {
				$mail_data['feedback_text'] .= "\r\n\r\nОтправлено со страницы: http://".$_SERVER['HTTP_HOST'].$this->catalog_service_model->get_item_link($p_data['item_id']);
				unset($p_data['item_id']);
			}

			$msg = $this->load->view('modules/feedback/email', $mail_data, true);

			$this->email->from($this->config->item('from_email'), $this->config->item('from_name'));
			$this->email->to($this->config->item('admin_email'));
			$this->email->subject('Сообщение обратной связи с сайта '.$this->config->item('company_name'));
			$this->email->message($msg);

			if ($this->email->send()) {
				if (!$this->input->post('XMLHttpRequest')) $this->session->set_flashdata('msg', 'Спасибо, Ваше сообщение отправлено.');
				$out['text'] = showmenotice("Спасибо, Ваше сообщение успешно отправлено.<br /> Наш менеджер свяжется с Вами в ближайшее время.<br /><a class='close' href='#'>Закрыть окно</a>");
			} else {
				if (!$this->input->post('XMLHttpRequest')) $this->session->set_flashdata('msg', 'Ошибка отправки сообщения.');
				$out['text'] = showmenotice("Ошибка отправки сообщения");
			}

			$hidden = sha1("soltbyme".$this->session->userdata('session_id')."mybigsolthash");
			$hidden2 = sha1("soltbyme".$this->session->userdata('session_id')."myhashsolt");
			unset($mail_data['item_id']);
			unset($mail_data[$hidden]);
			unset($mail_data[$hidden2]);
			unset($mail_data['XMLHttpRequest']);
			unset($mail_data[md5('showmemymoney')]);
			$mail_data['feedback_id'] = 0;
			$mail_data['feedback_date'] = time();
			$mail_data['feedback_ip'] = $this->input->ip_address();
			$this->db->insert('feedback', $mail_data);
			if (!$this->input->post('XMLHttpRequest'))
				redirect($this->url.'/');
			else
				return $out;
		}

		$form->insertInputSubmit('Отправить');

		if ($this->ion_auth->logged_in()) {
			$user = $this->ion_auth->get_user();
			$have_data['feedback_name'] = $user->first_name." ".$user->last_name;
			$have_data['feedback_phone'] = $user->phone;
			$have_data['feedback_email'] = $user->email;
		}

		$form->addDataSource(new HTML_QuickForm2_DataSource_Array($have_data));
		$data['form'] = $form."";
		$data['js'] = jQuickForm::js()->getJsAll();

		$out['text'] = $this->load->view('modules/feedback/index', $data, true);
		return $out;
	}
}